import type { Ref } from 'vue';
import type { Cell, Column } from '../types';

// 定义更具体的函数类型
type SaveStateFn = () => void;

export function useContextMenu(tableData: Ref<Cell[][]>, columns: Ref<Column[]>, saveState: SaveStateFn, emit: Function, props: any) {
  // 存储当前显示的上下文菜单引用
  let currentContextMenu: HTMLElement | null = null;
  // 存储事件监听器引用，以便清理
  let globalClickListener: ((e: MouseEvent) => void) | null = null;

  // 列标签生成函数
  const getColumnLabel = (index: number): string => {
    let label = '';
    let num = index;

    do {
      label = String.fromCharCode(65 + (num % 26)) + label;
      num = Math.floor(num / 26) - 1;
    } while (num >= 0);

    return label;
  };

  // 更新所有列标签
  const updateColumnLabels = () => {
    columns.value.forEach((column: Column, index: number) => {
      column.name = getColumnLabel(index);
    });
  };

  // 清空单元格
  const clearCell = (rowIndex: number, colIndex: number) => {
    tableData.value[rowIndex][colIndex].name = '';
    saveState();
  };

  // 添加行
  const addRowData = (position: 'top' | 'bottom', rowIndex: number) => {
    const newRow: Cell[] = Array(columns.value.length)
      .fill(null)
      .map((item: Cell) => ({
        name: '',
        id: '',
        type: '',
        brandId: '',
        customerId: ''
      }));

    if (position === 'top') {
      tableData.value.splice(rowIndex, 0, newRow);
    } else {
      tableData.value.splice(rowIndex + 1, 0, newRow);
    }
    saveState();
    emit('update:tableData', tableData.value);
    emit('update:addRow');
  };

  // 添加列
  const addColData = (position: 'left' | 'right', colIndex: number) => {
    const newColIndex = position === 'left' ? colIndex : colIndex + 1;
    tableData.value.forEach((row) => {
      row.splice(newColIndex, 0, {
        name: '',
        id: '',
        type: '',
        brandId: '',
        customerId: ''
      });
    });

    const newColumnName = getColumnLabel(newColIndex);
    columns.value.splice(newColIndex, 0, { name: newColumnName });

    updateColumnLabels();
    saveState();
    emit('update:tableData', tableData.value);
    emit('update:columns', columns.value);
    emit('update:addCol');
  };

  // 删除单元格数据（支持行、列、单元格）
  const deleteCellData = (rowIndex: number, colIndex: number) => {
    // 删除整行
    if (colIndex === -1) {
      if (tableData.value.length > 1) {
        tableData.value.splice(rowIndex, 1);
        saveState();
        emit('update:tableData', tableData.value);
      }
    }
    // 删除整列
    else if (rowIndex === -1) {
      if (columns.value.length > 1) {
        columns.value.splice(colIndex, 1);
        tableData.value.forEach((row) => {
          row.splice(colIndex, 1);
        });
        updateColumnLabels();
        saveState();
        emit('update:tableData', tableData.value);
        emit('update:columns', columns.value);
      }
    }
    // 清空单元格内容
    else {
      if (tableData.value[rowIndex] && tableData.value[rowIndex][colIndex]) {
        tableData.value[rowIndex][colIndex].name = '';
        tableData.value[rowIndex][colIndex].id = '';
        saveState();
      }
    }
  };

  // 修改 getAllMenus 函数的返回类型
  const getAllMenus = (rowIndex: number, colIndex: number) => {
    let menuItems: Array<{ label: string; color?: string }> = [];
    if (rowIndex === null) {
      menuItems = [
        {
          label: '插入列(左侧)'
        },
        {
          label: '插入列(右侧)'
        },
        {
          label: '删除此列',
          color: '#ff4757'
        }
      ];
    } else if (colIndex === null) {
      menuItems = [
        {
          label: '插入行(上方)'
        },
        {
          label: '插入行(下方)'
        },
        {
          label: '删除此行',
          color: '#ff4757'
        }
      ];
    } else {
      menuItems = [
        {
          label: '清空内容',
          color: 'red'
        },
        {
          label: '插入行(上方)'
        },
        {
          label: '插入行(下方)'
        },
        {
          label: '插入列(左侧)'
        },
        {
          label: '插入列(右侧)'
        }
      ];
    }
    return menuItems;
  };

  // 隐藏上下文菜单并清理事件监听器
  const hideContextMenu = () => {
    // 移除上下文菜单
    if (currentContextMenu && document.body.contains(currentContextMenu)) {
      document.body.removeChild(currentContextMenu);
      currentContextMenu = null;
    }

    // 移除全局点击监听器
    if (globalClickListener) {
      document.removeEventListener('click', globalClickListener);
      globalClickListener = null;
    }
  };

  // 显示上下文菜单
  const showContextMenu = (
    event: MouseEvent,
    menuItems: Array<{
      label: string;
      color?: string;
      action: () => void;
    }>
  ) => {
    hideContextMenu();

    const contextMenu = document.createElement('div');
    contextMenu.className = 'table-context-menu';
    contextMenu.style.cssText = `
    position: fixed;
    top: ${event.clientY}px;
    left: ${event.clientX}px;
    background: white;
    border: 1px solid #d0d7de;
    border-radius: 6px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 10000;
    min-width: 160px;
    padding: 4px 0;
    animation: fadeIn 0.15s ease-out;
  `;

    menuItems.forEach((item) => {
      const menuItem = document.createElement('div');
      menuItem.className = 'context-menu-item';
      menuItem.style.cssText = `
      padding: 8px 12px;
      cursor: pointer;
      font-size: 14px;
      color: #24292f;
      transition: all 0.1s ease;
    `;

      menuItem.textContent = item.label;

      // 根据操作类型设置颜色
      if (item.color) {
        menuItem.style.color = item.color;
      } else if (item.label.includes('删除') || item.label.includes('清空')) {
        menuItem.style.color = '#ff4757';
      }

      menuItem.addEventListener('mouseenter', () => {
        menuItem.style.backgroundColor = '#f0f0f0';
      });

      menuItem.addEventListener('mouseleave', () => {
        menuItem.style.backgroundColor = 'white';
      });

      menuItem.addEventListener('click', () => {
        item.action();
        hideContextMenu();
      });

      contextMenu.appendChild(menuItem);
    });

    document.body.appendChild(contextMenu);
    currentContextMenu = contextMenu;

    // 调整菜单位置以防止超出视窗
    const rect = contextMenu.getBoundingClientRect();
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;

    if (rect.right > windowWidth) {
      contextMenu.style.left = windowWidth - rect.width - 10 + 'px';
    }

    if (rect.bottom > windowHeight) {
      contextMenu.style.top = windowHeight - rect.height - 10 + 'px';
    }

    globalClickListener = (e: MouseEvent) => {
      if (currentContextMenu && !currentContextMenu.contains(e.target as Node)) {
        hideContextMenu();
      }
    };

    setTimeout(() => {
      if (globalClickListener) {
        document.addEventListener('click', globalClickListener);
      }
    }, 0);
  };

  // 添加映射函数，将菜单key转换为包含action的完整菜单项
  const mapKeysToActions = (menuKeys: Array<{ label: string; color?: string }>, rowIndex: number, colIndex: number) => {
    return menuKeys.map((item) => {
      const baseItem = {
        label: item.label,
        color: item.color
      };
      switch (item.label) {
        case '插入列(左侧)':
          return { ...baseItem, action: () => addColData('left', colIndex) };
        case '插入列(右侧)':
          return { ...baseItem, action: () => addColData('right', colIndex) };
        case '删除此列':
          return { ...baseItem, action: () => deleteCellData(-1, colIndex) };
        case '插入行(上方)':
          return { ...baseItem, action: () => addRowData('top', rowIndex) };
        case '插入行(下方)':
          return { ...baseItem, action: () => addRowData('bottom', rowIndex) };
        case '删除此行':
          return { ...baseItem, action: () => deleteCellData(rowIndex, -1) };
        case '清空内容':
          return { ...baseItem, action: () => clearCell(rowIndex, colIndex) };
        default:
          return {
            ...baseItem,
            action: () => {}
          };
      }
    });
  };

  // 处理上下文菜单事件
  const handleContextMenu = (event: MouseEvent, rowIndex: number, colIndex: number) => {
    event.preventDefault();
    event.stopPropagation();
    const menuKeys = getAllMenus(rowIndex, colIndex); // 获取菜单key列表

    let menuItems;
    if (props.onContextMenu) {
      // 父组件自定义菜单
      const customMenuKeys = props.onContextMenu(rowIndex, colIndex, menuKeys);
      // 根据key映射到实际的菜单项（包含action）
      menuItems = mapKeysToActions(customMenuKeys, rowIndex, colIndex);
    } else {
      // 使用默认菜单
      menuItems = mapKeysToActions(menuKeys, rowIndex, colIndex);
    }

    showContextMenu(event, menuItems);
  };

  // 清理函数 - 在组件销毁时调用
  const cleanup = () => {
    hideContextMenu();
  };

  const hideCurrentContextMenu = () => {
    hideContextMenu();
  };

  return {
    handleContextMenu,
    showContextMenu,
    getAllMenus,
    deleteCellData,
    clearCell,
    addRowData,
    addColData,
    updateColumnLabels,
    getColumnLabel,
    hideCurrentContextMenu,
    cleanup // 导出清理函数
  };
}
